<!--
	全国承灾体易损性数据
	Created by Penglei on 2023/08/10
-->
<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header :back="true" to="/vulnerability" />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <subheadings :name="'全国建筑物综合抗震能力分布图（' + level + '度基本完好）'" />
          <!-- 地图 -->
          <div class="app-map">
            <OlMap
              :sourchSeaZoom="2"
              :southSeaMapId="'geologicaldisaster1'"
              :sourchSeaStyles="{ position: 'absolute', bottom: '20px', width: '50px', height: '70px' }"
              refId="geologicaldisaster1"
              :center="[105, 36]"
              :zoom="3.2"
              :minZoom="3.2"
              style="height: 100%"
              @getMap="getMap1"
              @mapClick="mapClick1"
            ></OlMap>
          </div>
          <div style="display: flex; position: relative; margin-left: 30px; top: -80px; align-items: center">
            <div style="width: 20px; height: 12px; background-color: #ffc95d"></div>
            <span style="font-size: 14px; margin-left: 10px; color: #fff">{{ level }}度基本完好</span>
          </div>
        </div>
        <div class="app-left-item" style="">
          <subheadings :name="'全国建筑物综合抗震能力分布图（' + level + '度严重破坏）'" />
          <!-- 地图 -->
          <div class="app-map">
            <OlMap
              :sourchSeaZoom="2"
              :southSeaMapId="'geologicaldisaster2'"
              :sourchSeaStyles="{ position: 'absolute', bottom: '20px', width: '50px', height: '70px' }"
              refId="geologicaldisaster2"
              :center="[105, 36]"
              :zoom="3.2"
              :minZoom="3.2"
              style="height: 100%"
              @getMap="getMap4"
              @mapClick="mapClick4"
            ></OlMap>
          </div>
          <div style="display: flex; position: relative; margin-left: 30px; top: -80px; align-items: center">
            <div style="width: 20px; height: 12px; background-color: #FF6600"></div>
            <span style="font-size: 14px; margin-left: 10px; color: #fff">{{ level }}度严重破坏</span>
          </div>
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-left">
        <div class="app-left-item">
          <subheadings :name="'全国建筑物综合抗震能力分布图（' + level + '度轻微破坏）'" />
          <!-- 地图 -->
          <div class="app-map">
            <OlMap
              :sourchSeaZoom="2"
              :southSeaMapId="'geologicaldisaster3'"
              :sourchSeaStyles="{ position: 'absolute', bottom: '20px', width: '50px', height: '70px' }"
              refId="geologicaldisaster3"
              :center="[105, 36]"
              :zoom="3.2"
              :minZoom="3.2"
              style="height: 100%"
              @getMap="getMap2"
              @mapClick="mapClick2"
            ></OlMap>
          </div>
          <div style="display: flex; position: relative; margin-left: 30px; top: -80px; align-items: center">
            <div style="width: 20px; height: 12px; background-color: #FFB624"></div>
            <span style="font-size: 14px; margin-left: 10px; color: #fff">{{ level }}度轻微破坏</span>
          </div>
        </div>
        <div class="app-left-item" style="">
          <subheadings :name="'全国建筑物综合抗震能力分布图（' + level + '度倒塌）'" />
          <!-- 地图 -->
          <div class="app-map">
            <OlMap
              :sourchSeaZoom="2"
              :southSeaMapId="'geologicaldisaster4'"
              :sourchSeaStyles="{ position: 'absolute', bottom: '20px', width: '50px', height: '70px' }"
              refId="geologicaldisaster4"
              :center="[105, 36]"
              :zoom="3.2"
              :minZoom="3.2"
              style="height: 100%"
              @getMap="getMap5"
              @mapClick="mapClick5"
            ></OlMap>
          </div>
          <div style="display: flex; position: relative; margin-left: 30px; top: -80px; align-items: center">
            <div style="width: 20px; height: 12px; background-color: #FF2A00"></div>
            <span style="font-size: 14px; margin-left: 10px; color: #fff">{{ level }}度倒塌</span>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <subheadings :name="'全国建筑物综合抗震能力分布图（' + level + '度中等破坏）'" />
          <!-- 地图 -->
          <div class="app-map">
            <OlMap
              :sourchSeaZoom="2"
              :southSeaMapId="'geologicaldisaster5'"
              :sourchSeaStyles="{ position: 'absolute', bottom: '20px', width: '50px', height: '70px' }"
              refId="geologicaldisaster5"
              :center="[105, 36]"
              :zoom="3.2"
              :minZoom="3.2"
              style="height: 100%"
              @getMap="getMap3"
              @mapClick="mapClick3"
            ></OlMap>
          </div>
          <div style="display: flex; position: relative; margin-left: 30px; top: -80px; align-items: center">
            <div style="width: 20px; height: 12px; background-color: #FF9100"></div>
            <span style="font-size: 14px; margin-left: 10px; color: #fff">{{ level }}度中等破坏</span>
          </div>
        </div>
        <div class="app-right-item">
          <subheadings name="不同破坏等级对比" />
          <DestructionComparison></DestructionComparison>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="VulnerabilitySubpage1">
// 不同破坏等级对比
import DestructionComparison from './components/DestructionComparison';

// start
import OlMap from '@/components/Olmap';
import Legend from './components/Legend.vue';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon } from 'ol/style';
import Feature from 'ol/Feature';
import { Point, MultiLineString, LineString, Polygon } from 'ol/geom';
import Circle from 'ol/geom/Circle';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';

// start
import Overlay from 'ol/Overlay';
import { fromLonLat } from 'ol/proj'; // 导入 fromLonLat 函数
import { Select, Draw, Modify, Snap, Translate } from 'ol/interaction';
import Text from 'ol/style/Text';
import GeoJSON from 'ol/format/GeoJSON';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { getBaseDir,getChinaBaseMap } from '@/map/projMap.js';
import { getSeismicResistance } from '@/api/vulnerability';

// end
// start
const router = useRouter();
const mapInstance1 = ref(null);
const mapInstance2 = ref(null);
const mapInstance3 = ref(null);
const mapInstance4 = ref(null);
const mapInstance5 = ref(null);
const proviceLayer1 = ref(null);
const proviceLayer2 = ref(null);
const proviceLayer3 = ref(null);
const proviceLayer4 = ref(null);
const proviceLayer5 = ref(null);
const SeismicLayers1 = ref(new Map());
const SeismicLayers2 = ref(new Map());
const SeismicLayers3 = ref(new Map());
const SeismicLayers4 = ref(new Map());
const SeismicLayers5 = ref(new Map());
const chinaProvinceFeatures = ref(null);
const geoJson = ref(null);
const level = ref(6);
let timer;
onMounted(() => {
  console.log('onMounted');
  setTimeout(() => {
    getSeismicDataByLevel();
  }, 1000);
});
const getSeismicDataByLevel = () => {
  let proms = [];
  for (let i = 6; i <= 10; i++) {
    const prom = getSeismicResistance({ level: i });
    proms.push(prom);
  }
  Promise.all(proms).then((res) => {
    let promsLayer = [];
    res.forEach((item, index) => {
      let data = item.data;
      let prom = setFeatureData(data, index + 6);
      promsLayer.push(prom);
    });
    Promise.all(promsLayer).then((result) => {
      console.log('res====', result);
      //item:index+6级别的1-5个图的数组
      result.forEach((item, index) => {
        //data:index+6级别的第i个图
        item.forEach((data, i) => {
          data.setVisible(false);
          switch (i) {
            case 0:
              SeismicLayers1.value.set(index + 6, data);
              break;
            case 1:
              SeismicLayers2.value.set(index + 6, data);
              break;
            case 2:
              SeismicLayers3.value.set(index + 6, data);
              break;
            case 3:
              SeismicLayers4.value.set(index + 6, data);
              break;
            case 4:
              SeismicLayers5.value.set(index + 6, data);
              break;
          }
        });
      });
      SeismicLayers1.value.forEach((value, key) => {
        mapInstance1.value.addLayer(value);
      });
      SeismicLayers2.value.forEach((value, key) => {
        mapInstance2.value.addLayer(value);
      });
      SeismicLayers3.value.forEach((value, key) => {
        mapInstance3.value.addLayer(value);
      });
      SeismicLayers4.value.forEach((value, key) => {
        mapInstance4.value.addLayer(value);
      });
      SeismicLayers5.value.forEach((value, key) => {
        mapInstance5.value.addLayer(value);
      });
      change();
      setTimer();
    });
  });
};
const change = () => {
  mapInstance1.value.getLayers().forEach((layer) => {
    if (layer.get('level')) {
      if (layer.get('level') == level.value) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
  mapInstance2.value.getLayers().forEach((layer) => {
    if (layer.get('level')) {
      if (layer.get('level') == level.value) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
  mapInstance3.value.getLayers().forEach((layer) => {
    if (layer.get('level')) {
      if (layer.get('level') == level.value) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
  mapInstance4.value.getLayers().forEach((layer) => {
    if (layer.get('level')) {
      if (layer.get('level') == level.value) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
  mapInstance5.value.getLayers().forEach((layer) => {
    if (layer.get('level')) {
      if (layer.get('level') == level.value) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
};
const setTimer = () => {
  timer = setInterval(() => {
    level.value++;
    if (level.value > 10) {
      level.value = 6;
    }
    console.log('timer', level.value);
    change();
  }, 5000);
};

// 在组件销毁前停止定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
});
const setFeatureData = (data, level) => {
  let layers = [];
  //dataArray:level级的5个图
  const dataArray = Object.values(data);

  dataArray.forEach((item, index) => {
    //item:level级的index个图
    const geojsonFormat = new GeoJSonFormat();
    let chinaFeatures = geojsonFormat.readFeatures(geoJson.value);
    let features = [];
    let layer = new VectorLayer({
      source: new VectorSource(),
      zIndex: 1,
    });
    item.forEach((item1) => {
      let feature = chinaFeatures.find((feature) => {
        return feature.get('adcode') == item1.code;
      });
      if (feature) {
        feature.setStyle(getProviceStyle(feature, index));
        features.push(feature);
      }
    });
    layer.getSource().addFeatures(features);
    layer.set('level', level);
    layers.push(layer);
  });
  return new Promise((resolve) => {
    resolve(layers);
  });
};
const getProviceStyle = (feature, index) => {
  var color = [
    'rgba(255, 201, 93, 1)',
    'rgba(255, 182, 36, 1)',
    'rgba(255, 145, 0, 1)',
    'rgba(255,102,0)',
    'rgba(255, 42, 0, 1)',
  ];
  return new Style({
    fill: new Fill({
      color: color[index],
    }),
    stroke: new Stroke({
      color: 'rgba(10, 22, 139, 1)',
      width: 1,
    }),
    /*
    text: new Text({
      font: '10px Calibri,sans-serif',
      fill: new Fill({ color: '#fff' }),
      text: feature.get('name'),
    }),
    */
  });
};
const getMap1 = (map) => {
  mapInstance1.value = map.value;
  addProvinceNameLayer(mapInstance1);
  createProvinceLayer(mapInstance1, proviceLayer1);
  setupSelectInteraction(mapInstance1);
};
const getMap2 = (map) => {
  mapInstance2.value = map.value;
  addProvinceNameLayer(mapInstance2);
  createProvinceLayer(mapInstance2, proviceLayer2);
  setupSelectInteraction(mapInstance2);
};
const getMap3 = (map) => {
  mapInstance3.value = map.value;
  addProvinceNameLayer(mapInstance3);
  createProvinceLayer(mapInstance3, proviceLayer3);
  setupSelectInteraction(mapInstance3);
};
const getMap4 = (map) => {
  mapInstance4.value = map.value;
  addProvinceNameLayer(mapInstance4);
  createProvinceLayer(mapInstance4, proviceLayer4);
  setupSelectInteraction(mapInstance4);
};
const getMap5 = (map) => {
  mapInstance5.value = map.value;
  addProvinceNameLayer(mapInstance5);
  createProvinceLayer(mapInstance5, proviceLayer5);
  setupSelectInteraction(mapInstance5);
};
// 创建图层的函数
const createProvinceLayer = (mapInstance, provinceLayer) => {
  provinceLayer.value = new VectorLayer({
    source: new VectorSource(),

    zIndex: 1,
  });
  mapInstance.value.addLayer(provinceLayer.value);
  fetch(getBaseDir('china.json'))
    .then((response) => response.json()) // 将响应解析为 JSON 数据
    .then((geojson) => {
      geoJson.value = geojson;
      // 使用 GeoJSON 格式解析器将数据转换为 Features
      const geojsonFormat = new GeoJSonFormat();
      chinaProvinceFeatures.value = geojsonFormat.readFeatures(geojson);
      chinaProvinceFeatures.value.forEach((feature) => {
        feature.setStyle(
          new Style({
            stroke: new Stroke({
              color: 'rgba(10, 22, 139, 1)',
              width: 1,
            }),
            fill: new Fill({
              color: 'transparent',
            }),
          })
        );
      });
      provinceLayer.value.getSource().addFeatures(chinaProvinceFeatures.value);
    })
    .catch((error) => {
      console.error('Error fetching or processing GeoJSON:', error);
    });
};

function addProvinceNameLayer(mapInstance) {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 2,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '8px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}


const setupSelectInteraction = (mapInstance) => {
  mapInstance.value.on('click', (event) => {
    const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
    if (features.length > 0) {
      router.push({ path: '/vulnerability/subpage2' });
    }
  })
}

// end
</script>

<style scoped lang="scss">
.app-container {
  min-height: 1080px;
}

.app-main {
  justify-content: flex-start;

  .app-left,
  .app-right {
    margin-top: 30px;
    margin-left: 30px;
    width: 600px;

    // 板块
    &-item {
      height: 450px;

      .subheadings {
        width: 100%;
      }
    }
  }
}

.app-map {
  width: 100%;
  height: calc(100% - 65px);
  margin: 0 auto;
}
</style>
